<template>
  <div class="algorithm-table">
    <el-card class="search-card" v-show="showSearch">
      <el-form @submit.native.prevent :model="queryParams" ref="queryForm" :inline="true" style="margin-bottom: -18px; padding: 3px 0 0 0">
        <!--        <el-form-item prop="cs">-->
        <!--          <el-input v-model="queryParams.cs" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />-->
        <!--        </el-form-item>-->
        <el-form-item label-width="80px">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <div style="float: right">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t('search') }}</el-button>
          <el-button class="button-ty" icon="el-icon-refresh" @click="resetQuery">{{ $t('reset') }}</el-button>
        </div>
      </el-form>
    </el-card>

    <el-card class="table-card" style="border-radius: 0px">
      <el-row :gutter="10" style="margin-bottom: 16px">
        <el-col :span="1.5">
          <el-button type="success" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button plain icon="el-icon-close" size="small" @click="handleClose">关闭</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
      </el-row>
      <div class="data-table">
        <el-table v-loading="loading" :data="tableData" :row-key="getRowKey" :border="false" @selection-change="handleSelectionChange" ref="multipleTable">
          <el-table-column :reserve-selection="true" type="selection" width="55" align="center" />
          <el-table-column prop="eventName" label="事件名称" align="center"></el-table-column>
          <el-table-column prop="eventCode" label="事件编码" align="center" :show-overflow-tooltip="true"></el-table-column>
<!--          <el-table-column prop="riskLevel" label="风险等级" align="center"></el-table-column>-->
          <el-table-column label="风险等级" align="center" prop="riskLevel">
            <template slot-scope="scope">
              <el-tag :type="getRiskType(scope.row.riskLevel)">{{ scope.row.riskLevel }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="majorCode" label="分类编码" align="center"></el-table-column>
          <el-table-column prop="baseWeight" label="权重" align="center"></el-table-column>
          <el-table-column label="是否启用" align="center" prop="enabled">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enabled" :active-value="1" :inactive-value="0" @change="handleSwitchChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" align="center"></el-table-column>
          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="180">
            <template slot-scope="scope">
              <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="small" type="text" icon="el-icon-setting" @click="handleDesign(scope.row)">配置</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination style="margin-bottom: 20px" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>

    <el-dialog class="form-dialog" :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="事件名称" prop="eventName">
          <el-input v-model="form.eventName" placeholder="请输入事件名称" style="width: 400px" />
        </el-form-item>
        <el-form-item label="事件编码" prop="eventCode">
          <el-input v-model="form.eventCode" placeholder="请输入事件编码" :disabled="read" style="width: 400px" />
        </el-form-item>
        <el-form-item label="分类编码" prop="majorCode">
          <el-input v-model="form.majorCode" placeholder="请输入分类编码" style="width: 400px" :disabled="true" />
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="form.riskLevel" placeholder="请选择风险等级" style="width: 400px">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
<!--          <el-input v-model="form.riskLevel" placeholder="请选择风险等级" style="width: 400px" />-->
        </el-form-item>
        <el-form-item label="权重" prop="baseWeight">
          <el-input v-model="form.baseWeight" placeholder="请输入权重" style="width: 400px" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" :autosize="{ minRows: 3, maxRows: 5 }" style="width: 400px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-show="form.id">{{ $t('update') }}</el-button>
        <el-button type="primary" @click="submitForm" v-show="!form.id">{{ $t('add') }}</el-button>
        <el-button @click="cancel">{{ $t('cancel') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog class="form-dialog" :title="configurationTitle" :visible.sync="openConfiguration" width="600px" append-to-body>
      <el-form ref="configurationForm" :model="configurationForm" :rules="configurationRules" label-width="100px">
        <el-form-item label="表达式名称" prop="exprName">
          <el-input v-model="configurationForm.exprName" placeholder="请输入表达式名称" style="width: 400px" />
        </el-form-item>
        <el-form-item label="安全分类" prop="bizType">
          <el-select v-model="configurationForm.bizType" placeholder="请选择安全分类" style="width: 400px">
            <el-option
              v-for="item in configurationOptions"
              :key="item.majorCode"
              :label="item.majorName"
              :value="item.majorCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表达式内容" prop="exprContent">
          <AceEditor ref="codeEditor" :content.sync="configurationForm.exprContent" lang="groovy" codeStyle="chrome" :read-only="false" width="400px" height="200px"></AceEditor>
        </el-form-item>
          <el-row :gutter="10" v-for="(item, index) in configurationForm.fieldMappings" :key="index">
            <el-col :span="11">
              <el-form-item label="参数名" label-width="100px">
                <el-input v-model="item.paramName" placeholder="请输入参数名" style="width: 160px" />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="参数值" label-width="80px">
                <el-input v-model="item.paramValue" placeholder="请输入参数值" controls-position="right" style="width: 160px" />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="add-remove-icon">
              <el-button size="mini" type="success" v-if="index === 0" icon="el-icon-plus" @click="addItem" circle></el-button>
              <el-button size="mini" type="danger" v-else icon="el-icon-delete" @click="removeItem(index)" circle></el-button>
            </el-col>
          </el-row>
        <el-form-item label="表达式描述" prop="paramDesc">
          <el-input v-model="configurationForm.paramDesc" type="textarea" placeholder="表达式描述" :autosize="{ minRows: 3, maxRows: 5 }" style="width: 400px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfigurationForm">确认</el-button>
        <el-button @click="cancelConfiguration">{{ $t('cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSecurityCategoryList, getEventConfigList, addEventConfig, detailEventConfig, editEventConfig, removeEventConfig, detailExpr, expressConfig, getEnabled } from '@/api/private/configurationManagement';
import AceEditor from '@/views/components/editor/editor.vue';
export default {
  name: "algorithmTable",
  components: {
    AceEditor,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中事件名称
      eventNameData: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //是否只读
      read:false,
      // 显示搜索条件
      showSearch: true,
      tableData: [],
      dateRange: [],
      queryParams: {
        tenantId: 1,
        pageNum: 1,
        pageSize: 10,
        majorCode: null,
      },
      options: [{
        value: 'A',
        label: 'A'
      }, {
        value: 'B',
        label: 'B'
      }, {
        value: 'C',
        label: 'C'
      }],
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      rules: {
        eventCode: [{ required: true, message: "请输入事件编码", trigger: 'blur' }],
        eventName: [{ required: true, message: "请输入事件名称", trigger: 'blur' }],
        majorCode: [{ required: true, message: "请输入主要代码", trigger: 'blur' }],
        riskLevel: [{ required: true, message: "请选择风险等级", trigger: 'blur' }],
        baseWeight: [{ required: true, message: "请输入权重", trigger: 'blur' },
          {
            pattern: /^[1-9]\d*(\.\d+)?$|^0(\.\d+)?$/,  // 核心正则：匹配整数/小数
            message: '请输入正确的整数或小数（如：10、10.5）',
            trigger: ['blur', 'change']  // 失焦/值变化时触发校验
          }],
      },
      // 弹出层标题
      configurationTitle: '',
      // 是否显示弹出层
      openConfiguration: false,
      //表单参数
      configurationForm: {},
      configurationOptions:[],
      configurationRules: {
        exprName: [{ required: true, message: "请输入表达式名称", trigger: 'blur' }],
        bizType: [{ required: true, message: "请选择安全分类", trigger: 'blur' }],
        exprContent: [{ required: true, message: "请输入表达式内容", trigger: 'blur' }],
      }
    }
  },
  created() {
    // 页面加载时获取路由参数（字符串类型）
    this.queryParams.majorCode = this.$route.params.majorCode;
    this.getList()
  },
  mounted() {
  },
  methods: {
    // 风险等级映射到预设类型
    getRiskType(riskLevel) {
      switch (riskLevel) {
        case "A":
          return "danger";
        case "B":
          return "warning";
        case "C":
          return "success";
        default:
          return "default"; // 默认类型（灰色）
      }
    },
    // 添加一行
    addItem() {
      // 向rows数组末尾添加一个新对象
      this.configurationForm.fieldMappings.push({
        paramName: '',
        paramValue: ''
      });
    },

    // 删除当前行
    removeItem(index) {
      // 至少保留一行（避免删除全部）
      if (this.configurationForm.fieldMappings.length <= 1) {
        this.$message.warning('至少保留一行数据');
        return;
      }
      // 从数组中删除对应索引的行
      this.configurationForm.fieldMappings.splice(index, 1);
    },
    // 查询安全事件列表
    getList() {
      this.loading = true;
      getEventConfigList(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.loading = false;
    },
    getRowKey: (row) => row.id ? row.id.toString() : Math.random().toString(36).substring(2),
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tenantId: 1,
        eventCode: null,
        eventName: null,
        majorCode: null,
        riskLevel: null,
        baseWeight: null,
        description: null,
      };
      this.resetForm('form');
    },
    // 表单重置
    resetConfiguration() {
      this.configurationForm = {
        eventId: null,
        exprId: null,
        tenantId: 1,
        bizType: null,
        exprName: null,
        exprContent: null,
        paramDesc: null,
        fieldMappings: [
          { paramName: '', paramValue: '' }
        ],
      };
      this.resetForm('configurationForm');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm('queryForm');
      this.handleQuery();
    },
    //控制启用
    handleSwitchChange(row) {
      const data = {
        id: row.id,
        enabled: row.enabled,
      };
      getEnabled(data).then((response) => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    handleClose() {
      // 跳转回父页面，并带上 tab 参数（值为 safetyClassification）
      this.$router.push({
        path: '/managementFunction',
        query: { tab: 'safetyClassification' } // 关键：传递标签标识
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      // 选中时赋值数组，未选中时清空
      this.eventNameData = selection.length > 0
        ? selection.map((item) => item.eventName)
        : [];
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.read = false;
      this.form.majorCode = this.$route.params.majorCode;
      this.title = "新增安全事件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.read = true;
      const categoryId = row.id || this.ids;
      detailEventConfig(categoryId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改安全事件";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            editEventConfig(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t('updateSuccess'));
              this.open = false;
              this.getList();
            });
          } else {
            addEventConfig(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t('addSuccess'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let categoryIds = row.id || this.ids;
      let nameData = "";
      // 1. 处理单选（点击行内删除按钮）
      if (row && row.eventName) {
        nameData = row.eventName; // 直接取当前行的分类名称
      }
      // 2. 处理多选（选中多行后点击顶部删除按钮）
      else if (this.eventNameData && this.eventNameData.length > 0) {
        // 将数组转为字符串（如 "分类1、分类2"），避免显示数组格式
        nameData = this.eventNameData.join("，");
      }
      // 3. 兜底：无明确名称时显示 ID（避免空值）
      else {
        nameData = Array.isArray(categoryIds) ? categoryIds.join("、") : categoryIds;
      }
      // 4. 确认弹窗：若仍无数据，提示通用信息
      const confirmMsg = nameData
        ? this.$t('deleteEventMsg', { eventName: nameData })
        : this.$t('deleteEventMsg');
      this.$modal
        .confirm(confirmMsg)
        .then(function () {
          return removeEventConfig(categoryIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('delSuccess'));
          this.$refs.multipleTable.clearSelection();
          // 重置选中的名称数组，避免下次删除残留
          this.eventNameData = [];
        })
        .catch(() => {});
    },
    getConfigurationOptions() {
      const queryConfigurationOptionsParams = {
        tenantId: 1,
        pageNum: 1,
        pageSize: 999,
      }
      getSecurityCategoryList(queryConfigurationOptionsParams).then((response) => {
        this.configurationOptions = response.rows;
      });
    },
    /** 配置按钮操作 */
    handleDesign(row) {
      if (!row || row.exprId === undefined || row.exprId === null || row.exprId === "") {
      } else {
        detailExpr(row.exprId).then((response) => {
          if (response.data !== undefined && response.data !== null) {
            this.configurationForm = response.data;
          }
        }).catch((error) => {
          console.error("请求失败：", error);
          this.form = {};
        });
      }
      this.resetConfiguration();
      this.getConfigurationOptions();
      this.configurationForm.eventId = row.id;
      this.configurationForm.eventCode = row.eventCode;
      this.configurationTitle = "配置算法";
      this.openConfiguration = true;
    },
    /** 提交按钮 */
    submitConfigurationForm: function () {
      this.$refs['configurationForm'].validate((valid) => {
        if (valid) {
          expressConfig(this.configurationForm).then((response) => {
            this.$modal.msgSuccess(this.$t('updateSuccess'));
            this.openConfiguration = false;
            this.getList();
          });
        }
      });
    },
    // 取消按钮
    cancelConfiguration() {
      this.openConfiguration = false;
      this.resetConfiguration();
    },
  },
}
</script>

<style lang="scss" scoped>
.algorithm-table {
  z-index: 1;
  min-height: calc(100vh - (72 / 1080 * 100vh));
  background: rgba(0,11,61,0.8);
  padding: 10px;
}
.search-card {
  background: rgba(0,11,61,0.8);
  color: #fff;
  border: none;
  margin-bottom: 15px;
  padding: 3px 0;

  ::v-deep .el-input__inner {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(22, 93, 255, 0.5);
    color: #fff; /* 文字颜色 */
  }
  ::v-deep .el-range-editor--medium .el-range-input {
    background: none;
    color: #fff; /* 文字颜色 */
  }
}

.button-ty {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(22, 93, 255, 0.5);
  color: #fff; /* 文字颜色 */
}

.table-card {
  background: rgba(0,11,61,0.8);
  border: none;
}

.data-table {
  ::v-deep .el-table {
    border: none !important;
  }

  /* 2. 表头底下线条 */
  ::v-deep .el-table th.el-table__cell.is-leaf {
    border-bottom: none;
  }

  /* 2. 表头背景（列标题区域） */
  ::v-deep .el-table tr {
    background: rgba(22,93,255);
  }
  /* 2. 表头字体大小（列标题区域） */
  ::v-deep .el-table th.el-table__cell>.cell {
    //font-size: px2font(16);
    //border-right: none !important; /* 移除单元格右侧边框 */
    //border-left: none !important; /* 移除单元格左侧边框（通常默认无，但保险起见） */
  }

  /* 3. 表格体背景（数据行区域） */
  /* 3.1 普通行背景 */
  ::v-deep .el-table__body-wrapper,
  ::v-deep .el-table__row {
    background: rgba(0,11,61,0.79) !important; /* 普通行背景（示例：白色） */
  }
  /* 3.1 普通行字体大小 */
  ::v-deep .el-table td.el-table__cell div {
    //font-size: px2font(14);
  }
  /* 表格体单元格背景（确保与行背景一致） */
  ::v-deep .el-table__cell {
    //background-color: inherit !important; /* 继承行背景 */
    background: rgba(0,11,61,0.79) !important; /* 表格体文字颜色（可选） */
    border-right: none !important; /* 移除单元格右侧边框 */
    border-left: none !important; /* 移除单元格左侧边框（通常默认无，但保险起见） */
    border: 1px solid rgba(255,255,255,0.1);
    color: rgba(255,255,255,0.9);
  }

  /* 4. 行 hover 状态背景（鼠标悬停时） */
  ::v-deep .el-table__row:hover {
    background: rgba(22,93,255,0.4) !important; /* hover 背景（示例：淡蓝） */
  }

  /* 5. 表格边框颜色（可选：与背景色协调） */
  ::v-deep .el-table__border,
  ::v-deep .el-table-cell {
    background: rgba(0,11,61,0.79) !important; /* 边框颜色（示例：浅灰） */
  }

  ::v-deep .el-table--border::after, .el-table--group::after {
    width: 0 !important;
  }

  ::v-deep .el-table__fixed-right::before {
    height: 0 !important;
  }

  ::v-deep .el-table::before {
    height: 0 !important;
  }
  ::v-deep .el-button--text {
    color: #ffffff;
  }

  /* 1. 分页组件整体文字颜色（基础设置） */
  ::v-deep .el-pagination {
    color: #ffffff !important; /* 默认文字颜色（示例：深灰色） */
  }

  ::v-deep input.el-input__inner {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(22, 93, 255, 0.5);
    color: #ffffff;
  }

  ::v-deep button.btn-prev {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(22, 93, 255, 0.5);
    color: #ffffff;
  }

  ::v-deep button.btn-next {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(22, 93, 255, 0.5);
    color: #ffffff;
  }

  /* 2. 页码按钮文字颜色 */
  ::v-deep .el-pager li {
    color: #ffffff !important; /* 普通页码文字 */
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(22, 93, 255, 0.5) !important;
  }

  /* 3. 当前选中页码的文字颜色 */
  ::v-deep .el-pager li.active {
    background-color: #409EFF !important;
    color: #ffffff !important; /* 选中页码文字（通常与背景色对比） */
  }

  /* 4. 上一页/下一页按钮文字颜色 */
  ::v-deep .el-pagination__prev,
  ::v-deep .el-pagination__next {
    color: #ffffff !important; /* 箭头按钮文字 */
  }

  /* 5. 禁用状态（如第一页的"上一页"）的文字颜色 */
  ::v-deep .el-pagination__prev.is-disabled,
  ::v-deep .el-pagination__next.is-disabled {
    color: #ffffff !important; /* 禁用状态文字（示例：浅灰色） */
  }

  /* 6. 总条数/跳转文本的颜色（如"共 100 条"） */
  ::v-deep .el-pagination__total,
  ::v-deep .el-pagination__jump {
    color: #ffffff !important; /* 说明文字颜色 */
  }

  ::v-deep .pagination-container {
    background: none;
    margin-top: px2vh(10);
    margin-bottom: px2vh(20);
  }

  ::v-deep .el-input--medium .el-input__inner {
    height: 28px;
  }
}

::v-deep .el-dialog {
  margin-top: 8vh !important;
  background: rgba(0,11,61);
}
.form-dialog {
  ::v-deep .el-input__inner {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(22, 93, 255, 0.5);
    color: #fff; /* 文字颜色 */
  }
  ::v-deep .el-textarea__inner {
    background: rgba(255, 255, 255, 0.1);
    border-color: rgba(22, 93, 255, 0.5);
    color: #ffffff;
  }
  ::v-deep .el-dialog__title {
    color: #ffffff;
  }
  ::v-deep .el-dialog__headerbtn .el-dialog__close {
    color: #ffffff;
  }
  ::v-deep .el-form-item__label {
    color: #ffffff;
  }
}
</style>
